package cn.deathlock;

/**
 * 死锁案列  1线程把s1锁住 2线程把s2锁住 大家又都需要使用对方锁住资源 形成互相等待局面
 */
public class DeathLock {
    public static void main(String[] args) {
        StringBuffer s1=new StringBuffer();//安全的字符串
        StringBuffer s2=new StringBuffer();
        new Thread(new Runnable() {
            @Override
            public void run() {
               synchronized (s1){//锁住s1
                   try {
                       Thread.sleep(100);//让进程2得到使用cpu机会 形成死锁
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   s1.append(1);
                   s2.append("a");
                   synchronized (s2){//锁住s2
                       s1.append(2);
                       s2.append("b");
                       System.out.println(s1);
                       System.out.println(s2);
                   }
               }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s2){//锁住s1
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    s1.append(1);
                    s2.append("a");
                    synchronized (s1){//锁住s2
                        s1.append(2);
                        s2.append("b");
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();
    }
}
